<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :title="teacherParams.teacherId ? '修改教师信息' : '添加教师信息'"
      @cancel="visible = false"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="teacherParams" ref="formRef">
        <a-form-item
          field="teacherName"
          label="教师名称"
          :rules="[{ required: true, message: '教师名称不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="teacherParams.teacherName"
            placeholder="请输入教师名称"
          />
        </a-form-item>

        <a-form-item
          field="gender"
          label="性别"
          :rules="[{ required: true, message: '性别不能为空' }]"
          validate-trigger="blur"
        >
          <a-radio-group v-model="teacherParams.gender">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="0">女</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          label="电话号码"
          field="phone"
          :rules="[
            { required: true, message: '电话不能为空' },
            {
              required: true,
              validator: validatePhoneNumber,
              message: '请输入正确的电话号码',
            },
          ]"
          validate-trigger="blur"
        >
          <a-input v-model="teacherParams.phone" placeholder="请输入电话号码" />
        </a-form-item>

        <a-form-item
          v-if="teacherParams.teacherId"
          label="入职日期"
          field="hireDate"
        >
          <a-date-picker></a-date-picker>
        </a-form-item>

        <a-form-item v-show="!teacherParams.teacherId" label="出生日期">
          <a-date-picker v-model="teacherParams.dateOfBirth"></a-date-picker>
        </a-form-item>

        <a-form-item
          field="email"
          label="邮箱"
          :rules="[
            { required: true, message: '邮箱不能为空' },
            {
              type: 'email',
              required: true,
            },
          ]"
          validate-trigger="blur"
        >
          <a-input
            v-model="teacherParams.email"
            :style="{ width: '350px' }"
            placeholder="请输入邮箱"
            class="input-demo"
            :min="10"
            :max="100"
          />
        </a-form-item>

        <a-form-item
          field="teacherAvatar"
          label="教师照片"
          :rules="[{ required: true, message: '教师照片不能为空' }]"
          validate-trigger="blur"
        >
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            image-preview
            :limit="1"
            @before-upload="beforeUpload"
          />
        </a-form-item>

        <a-form-item
          field="position"
          label="职位"
          :rules="[{ required: true, message: '职位不能为空' }]"
          validate-trigger="blur"
        >
          <a-select
            v-model="teacherParams.position"
            :style="{ width: '320px' }"
            placeholder="请输入职位"
          >
            <a-option value="0">主班教师</a-option>
            <a-option value="1">副班教师</a-option>
            <a-option value="2">保育员</a-option>
            <a-option value="3">园长</a-option>
            <a-option value="4">其他</a-option>
          </a-select>
        </a-form-item>

        <a-form-item
          field="address"
          label="家庭地址"
          :rules="[{ required: true, message: '家庭地址不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            v-model="teacherParams.address"
            :style="{ width: '350px' }"
            placeholder="请输入家庭地址"
            class="input-demo"
            :min="10"
            :max="100"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-card>
      <a-space size="medium">
        <a-input-search
          :style="{ width: '280px' }"
          placeholder="请输入教师名称"
          search-button
          @search="getteacherList"
          v-model="keyword"
        />
        <a-button @click="openVisible" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>添加教师</template>
        </a-button>
        <a-popconfirm content="你确定要删除这些教师吗?" @ok="batchDelete">
          <a-button type="primary" status="danger">
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-popconfirm>
      </a-space>
    </a-card>
    <a-card>
      <a-table
        :data="teacherInfoArr"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="teacherId"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectTeacher"
      >
        <template #columns>
          <a-table-column
            title="教师名称"
            data-index="teacherName"
          ></a-table-column>
          <a-table-column title="性别" data-index="gender"></a-table-column>
          <a-table-column title="电话" data-index="phone"></a-table-column>
          <a-table-column title="邮箱" data-index="email"></a-table-column>
          <a-table-column title="绑定码" data-index="bindCode"></a-table-column>
          <a-table-column
            title="家庭地址"
            data-index="address"
          ></a-table-column>
          <a-table-column
            title="入职日期"
            data-index="hireDate"
          ></a-table-column>

          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  @click="editTeacher(record)"
                  type="outline"
                  size="mini"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                  <template #default>编辑</template>
                </a-button>
                <a-popconfirm
                  @ok="deleteTeacher(record.teacherId)"
                  content="你确定要删除吗?"
                >
                  <a-button size="mini" status="danger">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-pagination
        @change="getTeacherInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqTeacherList,
  reqteacherInfoPage,
  addTeacher,
  updateTeacher,
  reqBatchDeleteTeacherInfo,
  reqDeleteTeacherById,
} from '@/api/teacher/index'
import { IconDelete, IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import { reqUploadImage } from '@/api/publicApi'
// import { UploadRequest } from '@arco-design/web-vue';
let teacherInfoArr = ref([])
let total = ref<number>(0)
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<String>()
let selectTeacher = ref([])
let formRef = ref()
const fileList = ref([])
// let dateRange = ref()
const visible = ref(false)

const teacherParams = reactive({
  teacherId: null,
  teacherName: '',
  gender: 0,
  phone: '',
  email: '',
  bindCode: '',
  teacherAvatar: '',
  address: '',
  hireDate: [],
  position: '',
  educationLevel: 0,
  major: '',
  dateOfBirth: '',
  teachingExperience: 0,
  expertise: '',
  classId: 0,
  remarks: '',
})
onMounted(() => {
  getTeacherInfo()
})

// 文件上传成功的回调
const beforeUpload = async (file: File) => {
  const forms = new FormData()
  forms.append('image', file) // 获取上传图片信息
  let result = await reqUploadImage(forms) //上传图片至和后台文件中
  let obj = {
    url: getImageUrl(result), //格式化图片路径
  }
  fileList.value.push(obj) //将图片路径添加到fileList中
}

// 格式化图片路径
const getImageUrl = (imageUrl: any) => {
  if (imageUrl) {
    // 拼接后端服务器地址和图片地址
    return `http://localhost:8081${imageUrl}`
  }
}

// 获取用户数据
const getTeacherInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await reqTeacherList(pageNo.value, pageSize.value)
  if (result.status === 'OK') {
    teacherInfoArr.value = result.data.records
    total.value = result.data.total
  }
}

// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getTeacherInfo(pageNo.value)
}

// 通过标题搜索
const getteacherList = async () => {
  if (keyword.value) {
    let result: any = await reqteacherInfoPage(
      pageNo.value,
      pageSize.value,
      keyword.value,
    )
    if (result.status === 'OK') {
      teacherInfoArr.value = result.data.records
    }
  } else {
    getTeacherInfo()
  }
}

// 模态框点击确定
const handleBeforeOk = () => {
  teacherParams.teacherAvatar = fileList.value[0].url
  formRef.value.validate(async (r: any, _Record: any) => {
    if (r === undefined) {
      // 发送请求
      let result = null
      if (teacherParams.teacherId) {
        result = await updateTeacher(teacherParams)
      } else {
        let today = new Date()
        let month =
          today.getMonth() + 1 < 9 ? `0${today.getMonth()}` : today.getMonth()
        teacherParams.hireDate = `${today.getFullYear()}-${month}-${today.getDate()}`
        result = await addTeacher(teacherParams)
      }
      if (result.status === 'OK') {
        Message.success(result.message)
        getTeacherInfo()
        visible.value = false
      } else {
        Message.error(result.message)
      }
    }
  })
}

const validatePhoneNumber = (value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 中国手机号正则表达式
  if (!value || !phoneRegex.test(value)) {
    callback(new Error('请输入有效的电话号码'))
  } else {
    callback()
  }
}

// 打开模态框
const openVisible = () => {
  Object.assign(teacherParams, {
    teacherId: null,
    teacherName: '',
    gender: 0,
    phone: '',
    email: '',
    bindCode: '',
    teacherAvatar: '',
    address: '',
    hireDate: '',
    position: '',
    educationLevel: 0,
    major: '',
    teachingExperience: 0,
    dateOfBirth: '',
    expertise: '',
    classId: 0,
    remarks: '',
  })
  fileList.value = []
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  visible.value = true
}

const editTeacher = (_record: any) => {
  fileList.value = []
  Object.assign(teacherParams, _record)
  if (_record.teacherAvatar !== '') {
    fileList.value[0] = {
      url: _record.teacherAvatar,
    }
  }
  visible.value = true
}
const deleteTeacher = async (_recordId: any) => {
  let result: any = await reqDeleteTeacherById(_recordId)
  if (result.status === 'OK') {
    Message.success(result.message)
    getTeacherInfo(
      teacherInfoArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectTeacher.value.length < 1) {
    Notification.warning({
      title: '删除提示',
      content: '请选择你要删除的用户!',
    })
    return
  }
  let result = await reqBatchDeleteTeacherInfo(selectTeacher.value)
  if (result.status === 'OK') {
    Message.success(result.message)
    getTeacherInfo(pageNo.value)
  }
}
</script>

<style lang="scss" scoped></style>
